<template>
  <div class="add-team-page">
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="formData.name"
          name="name"
          label="队伍名称"
          placeholder="请填写队伍名称"
          :rules="[{ required: true, message: '请填写队伍名称' }]"
      />
    </van-cell-group>

    <van-cell-group inset>
      <van-field name="teamNum" label="队伍人数">
        <template #input>
          <van-stepper v-model="formData.maxNum" theme="round" button-size="20" max="10" min="2"/>
        </template>
      </van-field>
    </van-cell-group>


    <van-cell-group inset>
      <van-field
          v-model="formData.expireTime"
          is-link
          readonly
          name="datePicker"
          label="时间选择"
          placeholder="点击选择时间"
          @click="showPicker = true"
      />
      <van-popup v-model:show="showPicker" position="bottom">
        <van-date-picker @confirm="onConfirm" @cancel="showPicker = false" :min-date="minDate"/>
      </van-popup>
    </van-cell-group>

    <van-cell-group inset>
      <van-field
          v-model="statusText"
          is-link
          readonly
          name="status"
          label="队伍状态"
          placeholder="请选择队伍状态"
          @click="showStatusPicker = true"
      />
      <van-popup v-model:show="showStatusPicker" position="bottom">
        <van-picker
            :columns="statusOptions"
            @confirm="onStatusConfirm"
            @cancel="showStatusPicker = false"
        />
      </van-popup>
    </van-cell-group>
    
    <van-cell-group inset v-if="formData.status == 2">
      <van-field
          v-model="formData.password"
          name="password"
          label="队伍密码"
          placeholder="请输入6位数字密码"
          type="tel"
          maxlength="6"
          @input="handlePasswordInput"
          :rules="[
            { required: true, message: '请输入密码' },
            { pattern: /^\d{6}$/, message: '密码必须为6位数字' }
          ]"
      />
      <div class="password-hint">密码为6位数字</div>
    </van-cell-group>

    <van-cell-group inset>
      <van-field
          v-model="formData.description"
          rows="2"
          autosize
          label="队伍描述"
          type="textarea"
          maxlength="200"
          placeholder="请输入描述"
          show-word-limit
      />
    </van-cell-group>

    <!-- 标签选择 -->
    <van-cell-group inset>
      <div class="tags-section">
        <div class="tags-label">我的标签</div>
        <div class="tags-container">
          <div 
            v-for="(tag, index) in selectedTags" 
            :key="index"
            class="tag-item"
            :style="getTagStyle(tag)"
          >
            {{ tag }}
            <van-icon 
              name="cross" 
              size="12" 
              class="tag-delete-icon"
              @click.stop="removeTag(tag)"
            />
          </div>
          <div class="add-tag-button" @click="openTagPicker">
            <van-icon name="plus" size="16" />
            <span>选择标签</span>
          </div>
        </div>
      </div>
    </van-cell-group>

    <!-- 标签选择浮窗 -->
    <van-popup 
      v-model:show="showTagPicker" 
      position="bottom" 
      :style="{ height: '70%' }"
      round
    >
      <div class="tag-picker-container">
        <div class="tag-picker-header">
          <span class="tag-picker-title">选择标签</span>
          <van-button 
            type="primary" 
            size="small" 
            @click="confirmTags"
            :disabled="tempSelectedTags.length === 0"
          >
            完成
          </van-button>
        </div>
        
        <div class="tag-picker-content">
          <!-- 常用标签 -->
          <div class="common-tags-section">
            <div class="section-title">常用标签</div>
            <div class="tags-grid">
              <div
                v-for="tag in commonTags"
                :key="tag"
                class="tag-option"
                :class="{ 'tag-selected': tempSelectedTags.includes(tag) }"
                :style="getTagStyle(tag)"
                @click="toggleTag(tag)"
              >
                {{ tag }}
                <van-icon 
                  v-if="tempSelectedTags.includes(tag)" 
                  name="success" 
                  size="14" 
                  class="tag-check-icon"
                />
              </div>
            </div>
          </div>

          <!-- 自定义标签 -->
          <div class="custom-tag-section">
            <div class="section-title">自定义标签</div>
            <!-- 显示已添加的自定义标签 -->
            <div v-if="customTagsList.length > 0" class="tags-grid" style="margin-bottom: 12px;">
              <div
                v-for="tag in customTagsList"
                :key="tag"
                class="tag-option"
                :class="{ 'tag-selected': tempSelectedTags.includes(tag) }"
                :style="getTagStyle(tag)"
                @click="toggleTag(tag)"
              >
                {{ tag }}
                <van-icon 
                  v-if="tempSelectedTags.includes(tag)" 
                  name="success" 
                  size="14" 
                  class="tag-check-icon"
                />
              </div>
            </div>
            <!-- 输入框 -->
            <van-field
              v-model="customTagInput"
              placeholder="输入新标签后按回车添加"
              @keyup.enter="addCustomTag"
            >
              <template #button>
                <van-button 
                  size="small" 
                  type="primary" 
                  @click="addCustomTag"
                  :disabled="!customTagInput.trim()"
                >
                  添加
                </van-button>
              </template>
            </van-field>
          </div>
        </div>
      </div>
    </van-popup>

  </van-form>
  
  <!-- 底部按钮 -->
  <div class="submit-button-container">
    <van-button round block type="primary" native-type="submit" @click="onSubmit">
      创建队伍
    </van-button>
  </div>
  </div>
</template>

<script setup lang="ts">
//import {showToast} from "vant";


import {ref, computed} from "vue";
import {addTeam} from "../api/teamApi";
import {showToast} from "vant";
import {useRouter} from "vue-router";

const addTeamData = {
  name: "",
  description: "",
  expireTime: "",
  maxNum: 3,
  password: "",
  status: 0,
  tags: [] as string[]
}

const formData = ref({...addTeamData});

const router = useRouter();

// 状态选择器
const showStatusPicker = ref(false);
const statusOptions = [
  { text: '公开', value: 0 },
  { text: '私有', value: 1 },
  { text: '加密', value: 2 }
];
const statusText = ref('公开');

// 状态选择确认
const onStatusConfirm = ({ selectedOptions }: any) => {
  const selected = selectedOptions[0];
  formData.value.status = selected.value;
  statusText.value = selected.text;
  showStatusPicker.value = false;
  // 如果切换到非加密状态，清空密码
  if (selected.value != 2) {
    formData.value.password = '';
  }
};

// 处理密码输入，只允许数字
const handlePasswordInput = (value: string) => {
  // 只保留数字
  formData.value.password = value.replace(/\D/g, '');
};

// 标签相关
const selectedTags = ref<string[]>([]);
const showTagPicker = ref(false);
const tempSelectedTags = ref<string[]>([]);
const customTagInput = ref('');

// 计算自定义标签列表（不在常用标签中的已选标签）
const customTagsList = computed(() => {
  return tempSelectedTags.value.filter(tag => !commonTags.includes(tag));
});

// 常用标签列表
const commonTags = [
  'UI设计', '交互设计', 'Figma', '用户研究', '原型设计',
  '前端开发', '后端开发', '产品经理', '数据分析', '测试',
  'Java', 'Python', 'JavaScript', 'Vue', 'React',
  '项目管理', '运营', '设计', '开发', '测试'
];

// 标签颜色配置
const tagColors = [
  { bg: '#E3F2FD', text: '#1976D2' }, // 浅蓝
  { bg: '#F3E5F5', text: '#7B1FA2' }, // 浅紫
  { bg: '#E8F5E9', text: '#388E3C' }, // 浅绿
  { bg: '#FFF3E0', text: '#F57C00' }, // 浅黄/橙
  { bg: '#E1F5FE', text: '#0277BD' }, // 浅蓝2
  { bg: '#FCE4EC', text: '#C2185B' }, // 浅粉
  { bg: '#F1F8E9', text: '#689F38' }, // 浅绿2
  { bg: '#FFF8E1', text: '#F9A825' }, // 浅黄
  { bg: '#E0F2F1', text: '#00796B' }, // 浅青
  { bg: '#EDE7F6', text: '#512DA8' }, // 浅紫2
];

// 获取标签样式
const getTagStyle = (tag: string) => {
  // 根据标签文本的hash值选择颜色
  let hash = 0;
  for (let i = 0; i < tag.length; i++) {
    hash = tag.charCodeAt(i) + ((hash << 5) - hash);
  }
  const colorIndex = Math.abs(hash) % tagColors.length;
  const color = tagColors[colorIndex];
  return {
    backgroundColor: color.bg,
    color: color.text
  };
};

// 切换标签选择状态
const toggleTag = (tag: string) => {
  const index = tempSelectedTags.value.indexOf(tag);
  if (index > -1) {
    tempSelectedTags.value.splice(index, 1);
  } else {
    tempSelectedTags.value.push(tag);
  }
};

// 添加自定义标签
const addCustomTag = () => {
  const tag = customTagInput.value.trim();
  if (tag && !tempSelectedTags.value.includes(tag)) {
    // 如果标签已经在常用标签中，直接选中；否则添加为自定义标签
    tempSelectedTags.value.push(tag);
    customTagInput.value = '';
  } else if (tag && tempSelectedTags.value.includes(tag)) {
    showToast('该标签已选择');
    customTagInput.value = '';
  }
};

// 打开标签选择器时，初始化临时选中标签
const openTagPicker = () => {
  tempSelectedTags.value = [...selectedTags.value];
  showTagPicker.value = true;
};

// 确认标签选择
const confirmTags = () => {
  selectedTags.value = [...tempSelectedTags.value];
  formData.value.tags = [...tempSelectedTags.value];
  showTagPicker.value = false;
  customTagInput.value = '';
};

// 删除标签
const removeTag = (tag: string) => {
  const index = selectedTags.value.indexOf(tag);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
    formData.value.tags = [...selectedTags.value];
  }
};


//时间选择器
const minDate = new Date();//默认起始时间
minDate.setDate(minDate.getDate() + 1);


const showPicker = ref(false);
const onConfirm = ({ selectedValues }: any) => {
  formData.value.expireTime = selectedValues.join('-') + " " + "00:00:00";
  showPicker.value = false;
};



//表单提交方法
const onSubmit = () => {
  addTeam(formData.value).then((res: any) =>{
    if (res.code == 200){
      //创建成功
      showToast("队伍创建成功");
      router.replace("/team");
    }else {
      console.log(res);
      //创建失败
      showToast("创建失败");
    }
  }).catch(() =>{
    //创建失败
    showToast("队伍创建失败");
  });
};


</script>

<style scoped>
.add-team-page {
  padding-bottom: 80px;
  min-height: 100vh;
  background-color: #f7f8fa;
}

.password-hint {
  padding: 8px 16px;
  font-size: 12px;
  color: #969799;
  text-align: left;
}

.submit-button-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 16px;
  background-color: #fff;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
  z-index: 100;
}

/* 标签相关样式 */
.tags-section {
  padding: 16px;
}

.tags-label {
  font-size: 14px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 12px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.tag-item {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 6px 24px 6px 12px;
  border-radius: 16px;
  font-size: 13px;
  font-weight: 400;
  white-space: nowrap;
}

.tag-delete-icon {
  position: absolute;
  top: -4px;
  right: 4px;
  cursor: pointer;
  opacity: 0.7;
  transition: opacity 0.2s;
  background-color: rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  padding: 2px;
}

.tag-delete-icon:hover {
  opacity: 1;
}

.tag-delete-icon:active {
  opacity: 0.9;
  transform: scale(0.9);
}

.add-tag-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 13px;
  color: #969799;
  background-color: #f7f8fa;
  border: 1px dashed #dcdee0;
  cursor: pointer;
  transition: all 0.2s;
}

.add-tag-button:active {
  background-color: #ebedf0;
}

/* 标签选择浮窗 */
.tag-picker-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #fff;
}

.tag-picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebedf0;
}

.tag-picker-title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

.tag-picker-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.common-tags-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 14px;
  font-weight: 500;
  color: #646566;
  margin-bottom: 12px;
}

.tags-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-option {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 14px;
  border-radius: 16px;
  font-size: 13px;
  font-weight: 400;
  cursor: pointer;
  transition: all 0.2s;
  border: 2px solid transparent;
}

.tag-option:active {
  transform: scale(0.95);
}

.tag-selected {
  border-color: currentColor;
  opacity: 0.9;
}

.tag-check-icon {
  margin-left: 4px;
}

.custom-tag-section {
  margin-top: 24px;
}
</style>